package infos

import (
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/common"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/groupd"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/infod"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/ddd"
)

type respGroup struct {
	Owner     string           `json:"owner"`      // 所属用户
	Org       string           `json:"org"`        // 所属组织
	Kind      groupd.GroupKind `json:"kind"`       // 类型（0,手动，1自动）
	Name      string           `json:"name"`       // 组名称
	ShortName string           `json:"short_name"` // 简称
	Icon      []string         `json:"icon"`       // 图标
	Desc      string           `json:"desc"`       // 简介
	InfoNum   int              `json:"info_num"`   // 组内信息数量
}

// 分页获取信息列表
func (c infoCtrl) getGroupInfoList(ctx *gin.Context) {

	page := c.GetPageInfo(ctx, common.PageModeID)
	dctx := c.DDDContext(ctx)
	groupid := ctx.Param("groupid")
	if groupid == "" {
		c.ErrBadRequest(ctx, 1, "没有设置组编号")
		return
	}
	ga, ok := c.getCheckGroup(ctx, dctx, groupid)
	if !ok {
		return
	}
	pr, gis, err := ga.QueryInfoPage(dctx, page)
	if err != nil {
		c.ErrServerError(ctx, 2, "查找信息列表失败", errors.Wrap(err, "查找信息列表失败"))
		return
	}
	respInfos, err := c.fullGroupInfo(ctx, dctx, gis)
	if err != nil {
		return
	}
	c.SuccessPage(ctx, page, pr, respInfos)
}

// 分页获取信息列表
func (c infoCtrl) getGroupInfoList4Key(ctx *gin.Context) {

	page := c.GetPageInfo(ctx, common.PageModeID)
	dctx := c.DDDContext(ctx)
	flags := c.ParamArray(ctx, "flags")
	if len(flags) == 0 {
		c.ErrBadRequest(ctx, 1, "没有设置组访问标识")
		return
	}

	sch := groupd.GroupSearch{
		Flags:  flags,
		Kind:   groupd.GroupKindAll,
		Range:  1,
		Status: []groupd.GStatus{groupd.GSNormal, groupd.GSStop},
	}

	pr, gis, err := c.gar.QueryInfoPageBySch(dctx, sch, page)
	if err != nil {
		c.ErrServerError(ctx, 2, "查找信息列表失败", errors.Wrap(err, "查找信息列表失败"))
		return
	}
	respInfos, err := c.fullGroupInfo(ctx, dctx, gis)
	if err != nil {
		return
	}
	c.SuccessPage(ctx, page, pr, respInfos)
}

// 获取query中的信息组查询参数
func (c infoCtrl) getGroupSearch(ctx *gin.Context) (result groupd.GroupSearch) {
	result.Range = c.GetIntByQuery(ctx, "range", 0)
	result.Owner = ctx.DefaultQuery("owner", "")
	result.Org = ctx.DefaultQuery("org", "")
	result.Key = ctx.DefaultQuery("key", "")
	result.Status = []groupd.GStatus{groupd.GSNormal}
	return
}

// 分页获取符合条件的组列表
func (c infoCtrl) getGroups(ctx *gin.Context) {

	page := c.GetPageInfo(ctx, common.PageModeID)
	sch := c.getGroupSearch(ctx)
	dctx := c.DDDContext(ctx)
	page.Mode = 1
	pr, gs, err := c.gar.QueryPage(dctx, sch, page)
	if err != nil {
		c.ErrServerError(ctx, 2, "查找组列表失败", errors.Wrap(err, "查找组列表失败"))
		return
	}
	if len(gs) == 0 {
		c.Success(ctx, nil)
		return
	}
	rs := make([]respGroup, 0, len(gs))
	for _, ga := range gs {
		r := respGroup{
			Owner:     ga.Owner,
			Org:       ga.Org,
			Kind:      ga.Kind,
			Name:      ga.Name,
			ShortName: ga.ShortName,
			Icon:      ga.Icon,
			Desc:      ga.Desc,
			InfoNum:   ga.InfoNum,
		}
		rs = append(rs, r)
	}
	c.SuccessPage(ctx, page, pr, rs)
}

// 分页获取信息列表
func (c infoCtrl) getGroupInfos(ctx *gin.Context) {

	page := c.GetPageInfo(ctx, common.PageModeID)
	sch := c.getGroupSearch(ctx)
	dctx := c.DDDContext(ctx)
	page.Mode = 1
	pr, gis, err := c.gar.QueryInfoPageBySch(dctx, sch, page)
	if err != nil {
		c.ErrServerError(ctx, 2, "查找信息列表失败", errors.Wrap(err, "查找信息列表失败"))
		return
	}
	respInfos, err := c.fullGroupInfo(ctx, dctx, gis)
	if err != nil {
		return
	}
	c.SuccessPage(ctx, page, pr, respInfos)
}
func (c infoCtrl) fullGroupInfo(ctx *gin.Context, dctx ddd.Context, gis []groupd.GroupInfoEntity) (respInfos []interface{}, err error) {

	cs := make([]infod.InfoAggregate, 0, len(gis))
	//ids := make([]string, 0, len(gis))
	for _, v := range gis {
		i, err1 := c.iar.GetInfo(dctx, v.InfoID)
		if err1 != nil {
			c.ErrServerError(ctx, 31, "查找信息失败", errors.Wrap(err1, "查找信息列表失败"))
			err = err1
			return
		}
		cs = append(cs, *i)
	}
	if err != nil {
		c.ErrServerError(ctx, 32, "查找信息列表失败", errors.Wrap(err, "查找信息列表失败"))
		return
	}
	respInfos = make([]interface{}, 0, len(cs))
	for i, v := range cs {
		col, err1 := c.car.GetColumn(dctx, v.ColumnID)
		if err1 != nil {
			c.ErrServerError(ctx, 33, "查询文章所在栏目信息失败", errors.Wrapf(err, "查询信息(%v)所在栏目信息失败.", v.InfoID))
			err = err1
			return
		}
		respInfos = append(respInfos, adapterG2Resp(ctx, &v, &gis[i], col))
	}
	return
}

// 获取组信息
func (c infoCtrl) getGroup(ctx *gin.Context) {

	groupid := ctx.Param("groupid")
	if groupid == "" {
		c.ErrBadRequest(ctx, 1, "没有设置组编号")
		return
	}
	dctx := c.DDDContext(ctx)
	ga, ok := c.getCheckGroup(ctx, dctx, groupid)
	if !ok {
		return
	}

	c.Success(ctx, &respGroup{
		Owner:     ga.Owner,
		Org:       ga.Org,
		Kind:      ga.Kind,
		Name:      ga.Name,
		ShortName: ga.ShortName,
		Icon:      ga.Icon,
		Desc:      ga.Desc,
		InfoNum:   ga.InfoNum,
	})
}

func (c infoCtrl) getCheckGroup(ctx *gin.Context, dctx ddd.Context, groupid string) (ga *groupd.GroupAggregate, ok bool) {
	ga, err := c.gar.GetGroup(dctx, groupid)
	if err != nil {
		c.ErrServerError(ctx, 21, "获取信息组失败", errors.Wrapf(err, "检测信息组(%v)是否存在失败：", groupid))
		return
	}
	if ga == nil {
		c.ErrNotFound(ctx, 22, "信息组不存在", nil)
		return
	}
	if ga.Status == groupd.GSDeleted {
		c.ErrBadRequest(ctx, 23, "信息组已经被删除")
		return
	}
	ok = true
	return
}
